﻿using System;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace Agile.Service.Rbac {
    public class OnlineUserHub:Hub<IOnlineUser> {
        private readonly IUserOnlineService _onlineUserService;
        private readonly ILoginInfo _loginInfo;
        public OnlineUserHub(IUserOnlineService onlineUserService,ILoginInfo loginInfo) {
            _onlineUserService = onlineUserService;
            _loginInfo = loginInfo;
        }
        public async Task SendMessage(string user,string message) {
            await Clients.User(user).ReceiveMessage(_loginInfo.AccountId,_loginInfo.AccountName,message);
        }
        public override Task OnConnectedAsync() {
            //添加在线用户           
            RegistryOnlineUser();
            Clients.Others.Online(new {
                Context.ConnectionId,
                _loginInfo.AccountId,
                _loginInfo.AccountName,
                OnlineState = UserOnline.CONST_ONLINE
            });
            return base.OnConnectedAsync();
        }
        private void RegistryOnlineUser() {
            UserOnline onlineUser = new UserOnline() {
                AccountId = _loginInfo.AccountId,
                AccountName = _loginInfo.AccountName,
                ClientIP = _loginInfo.ClientIP,
                LoginTime = _loginInfo.LoginTime,
                ConnectionId = !string.IsNullOrWhiteSpace(Context.ConnectionId) ? Context.ConnectionId : "",
                OnlineState = UserOnline.CONST_ONLINE
            };
            _onlineUserService.OnlineUser(onlineUser);
        }
        public override Task OnDisconnectedAsync(Exception exception) {
            //添加离线用户
            Clients.Others.Offline(new {
                Context.ConnectionId,
                _loginInfo.AccountId,
                _loginInfo.AccountName,
                OnlineState = UserOnline.CONST_OFFLINE
            });
            _onlineUserService.OfflineUser(Context.ConnectionId);
            return base.OnDisconnectedAsync(exception);
        }
        public IPrincipal ClientContextUser {
            get { return Context.User; }
        }
    }
}
